import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { User } from '@/types';
import * as authService from '@/services/auth';

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  updateUser: (user: User) => void;
  checkAuth: () => Promise<boolean>;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,

      login: async (email: string, password: string) => {
        console.log('🔑 开始登录:', { email });
        
        try {
          const result = await authService.login({ email, password });
          console.log('✅ 登录API调用成功:', { 
            hasUser: !!result.user, 
            hasToken: !!result.token,
            userId: result.user?.id 
          });
          
          set({
            user: result.user,
            token: result.token,
            isAuthenticated: true,
          });
          
          console.log('✅ 登录状态已更新:', {
            isAuthenticated: true,
            userId: result.user?.id,
            username: result.user?.username
          });
          
        } catch (error) {
          console.error('❌ 登录失败:', error);
          set({
            user: null,
            token: null,
            isAuthenticated: false,
          });
          throw error;
        }
      },

      logout: async () => {
        console.log('👋 开始退出登录');
        
        try {
          // 调用后端登出接口
          await authService.logout();
          console.log('✅ 后端登出成功');
        } catch (error) {
          console.error('❌ 登出接口调用失败:', error);
        } finally {
          // 无论后端调用是否成功，都清除本地状态
          set({
            user: null,
            token: null,
            isAuthenticated: false,
          });
          
          console.log('🗑️ 本地状态已清除');
          
          // 跳转到登录页
          window.location.href = '/login';
        }
      },

      updateUser: (user: User) => {
        console.log('👤 更新用户信息:', { userId: user.id, username: user.username });
        set({ user });
      },

      checkAuth: async () => {
        const { token } = get();
        console.log('🔍 检查认证状态:', { hasToken: !!token });
        
        if (!token) {
          console.log('❌ 没有token，设置为未认证');
          set({ isAuthenticated: false });
          return false;
        }

        try {
          console.log('📡 调用获取用户信息API...');
          // 验证token是否有效，获取最新用户信息
          const user = await authService.getCurrentUser();
          console.log('✅ 获取用户信息成功:', { 
            userId: user.id, 
            username: user.username,
            role: user.role 
          });
          
          set({
            user,
            isAuthenticated: true,
          });
          
          console.log('✅ 认证状态已更新为已认证');
          return true;
        } catch (error) {
          console.error('❌ 验证身份失败:', error);
          set({
            user: null,
            token: null,
            isAuthenticated: false,
          });
          console.log('❌ 认证状态已更新为未认证');
          return false;
        }
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        token: state.token,
        user: state.user,
        // 不保存 isAuthenticated，让它根据 token 动态计算
      }),
      onRehydrateStorage: () => (state, error) => {
        console.log('💾 从本地存储恢复状态:', {
          hasToken: !!state?.token,
          hasUser: !!state?.user,
          error
        });
        
        // 恢复后重新计算认证状态
        if (state?.token && state?.user) {
          console.log('🔄 恢复后设置认证状态为true');
          return {
            ...state,
            isAuthenticated: true,
          };
        } else {
          console.log('🔄 恢复后设置认证状态为false');
          return {
            ...state,
            isAuthenticated: false,
          };
        }
      },
    }
  )
); 